package test;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: LIUTENG
 * Date: 14-3-12
 * Time: 上午10:10
 * To change this template use File | Settings | File Templates.
 */
public class CalendarSearch {

    public static void main(String[] args) {
        FindSpecialDate(2000, 2020, 4, 6);
    }

    /**
     * 查找指定时间段内满足特定条件的日子
     * @param startYear   开始查找年份
     * @param endYear    结束查找年份
     * @param countInYearLimit   一年中满足条件的次数
     * @param dayOfWeek   查找星期几，星期日为1，以此类推
     */
    private static void FindSpecialDate(int startYear, int endYear, int countInYearLimit, int dayOfWeek) {
        Calendar cld = Calendar.getInstance();
        cld.set(Calendar.YEAR, startYear);
        cld.set(Calendar.MONTH, 0);
        cld.set(Calendar.DATE, 1);
        int currentYear = cld.get(Calendar.YEAR);
        int countInYear = 0;
        List<Date> dateInYear = new ArrayList<Date>();
        do {
            cld = getNextDay(cld);
            if (currentYear != cld.get(Calendar.YEAR)) {
                currentYear = cld.get(Calendar.YEAR);
                if (dateInYear.size() > 0 && countInYear > countInYearLimit) {
                    System.out.println("---------------------------------------------------------");
                    printYearInfo(dateInYear);
                }
                countInYear = 0;
                dateInYear.clear();
            }
            if ((cld.get(Calendar.MONTH) + 1) == cld.get(Calendar.DATE) && cld.get(Calendar.DAY_OF_WEEK) == dayOfWeek) {
                countInYear++;
                dateInYear.add(cld.getTime());
            }
        } while (cld.get(Calendar.YEAR) != endYear);
    }

    /**
     * 打印一年中满足条件的List<Date>
     * @param dateInYear 一年中满足条件的List<Date>
     */
    private static void printYearInfo(List<Date> dateInYear) {
        for (Date date:dateInYear) {
            System.out.println(new SimpleDateFormat("yyyy-MM-dd E").format(date));
        }
    }

    /**
     * 获取后一天的日子实例
     * @param cld 日历实例
     * @return 后一天
     */
    private static Calendar getNextDay(Calendar cld) {
        cld.add(Calendar.DATE, 1);
        return cld;
    }
}
